<template>
  <div class="nav">
    <template>
      <div class="layout">
        <Layout>
          <Header>
            <Menu mode="horizontal" theme="dark" active-name="1">
              <div class="layout-logo">
                <router-link to="/home">未来社区</router-link>
              </div>
              <div class="top-list">
                <RadioGroup v-model="pageNow" type="button" fill="#2D8CF0">
                  <Radio label="首页"  @click.once.native="$router.push('/')"></Radio>
                  <Radio label="话题分类" @click.once.native="toCategory"></Radio>
                  <Radio label="我参与的话题"></Radio>
                </RadioGroup>
              </div>
              <div class="layout-nav">
                <MenuItem name="3">
                  <RadioGroup v-model="searchBy">
        <Radio label="title">标题搜索</Radio>
        <Radio label="body">内容搜索</Radio>
    </RadioGroup>
                  <Input
                    class="search"
                    v-model="search"
                    placeholder="搜索"
                    style="width: 80px"
                  />
                  <Icon type="md-search" @click="searchList" />
                </MenuItem>
                <MenuItem name="4">
                  <img class="userImg" :src="userInfo.avatar" />
                  <Dropdown
                    trigger="click"
                    :transfer="true"
                    style="margin-left: 20px"
                  >
                    <a href="javascript:void(0)" style="color: white">
                      {{ userInfo.username}}
                      <Icon type="ios-arrow-down"></Icon>
                    </a>
                    <DropdownMenu slot="list">
                      <DropdownItem>
                        <router-link class="link-to-per" to="/personal"
                          >个人中心</router-link
                        >
                      </DropdownItem>
                      <!-- <DropdownItem>北京烤鸭</DropdownItem> -->
                      <DropdownItem @click.native="pwView = true"
                        >修改密码</DropdownItem
                      >
                      <DropdownItem
                        > <router-link class="link-to-per" to="/perinfo"
                          >修改信息</router-link
                        ></DropdownItem
                      >
                      <DropdownItem @click.native="imgView = true"
                        >修改头像</DropdownItem
                      >
                      <DropdownItem @click.native="exitLogin"
                        >退出登录</DropdownItem
                      >
                    </DropdownMenu>
                  </Dropdown>
                </MenuItem>
              </div>
            </Menu>
          </Header>
        </Layout>
        <Modal
          v-model="imgView"
          width="360"
          :transfer="false"
          :mask-closable="false"
        >
          <p slot="header" style="color: #f60; text-align: center">
            <span>请选择头像</span>
          </p>
          <div style="text-align: center">
            <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-change="changeUpload"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
                @click.stop="dialogVisible = true"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </div>
          <el-dialog
            title="图片剪裁"
            :visible.sync="dialogVisible"
            append-to-body
          >
            <div class="cropper-content">
              <div class="cropper" style="text-align: center">
                <vueCropper
                  ref="cropper"
                  :img="option.img"
                  :outputSize="option.size"
                  :outputType="option.outputType"
                  :info="true"
                  :full="option.full"
                  :canMove="option.canMove"
                  :canMoveBox="option.canMoveBox"
                  :original="option.original"
                  :autoCrop="option.autoCrop"
                  :fixed="option.fixed"
                  :fixedNumber="option.fixedNumber"
                  :centerBox="option.centerBox"
                  :infoTrue="option.infoTrue"
                  :fixedBox="option.fixedBox"
                ></vueCropper>
              </div>
            </div>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="finish" :loading="loading"
                >确认</el-button
              >
            </div>
          </el-dialog>
          <div slot="footer">
            <Button type="error" size="large" long @click="cImg(imgFile.raw)"
              >确认</Button
            >
          </div>
        </Modal>
        <Modal
          class="pwsWrap"
          v-model="pwView"
          width="360"
          :transfer="false"
          :mask-closable="false"
          @on-ok="changePasswords"
        >
          <p slot="header">修改密码</p>
          <p>
            <Input
              v-model="passwords.originalPassword"
              type="password"
              password
              placeholder="请输入原密码"
              style="width: 250px"
            />
          </p>
          <p>
            <Input
              v-model="passwords.password"
              type="password"
              password
              placeholder="请输入新密码"
              style="width: 250px"
            />
          </p>
          <p>
            <Input
              v-model="passwords.confirmPassword"
              type="password"
              password
              placeholder="请确认新密码"
              style="width: 250px"
            />
          </p>
        </Modal>
      </div>
    </template>
  </div>
</template>

<script>
// import {mapState} from "vuex"
export default {
  name: "Nav",
  data() {
    return {
      userInfo:{},
      pwView: false,
      imgView: false,
      imageUrl: "",
      imgFile: "",
      search: "",
      searchBy:"title",
      passwords: {
        originalPassword: "",
        password: "",
        confirmPassword: "",
      },
      // pageNow: "首页",
      dialogVisible: false, //裁减框的显示
      // 裁剪组件的基础配置option
      option: {
        img: "", // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 0.8, // 裁剪生成图片的质量
        outputType: "jpg", // 裁剪生成图片的格式
        canScale: false, // 图片是否允许滚轮缩放
        autoCrop: true, // 是否默认生成截图框
        // autoCropWidth: 300, // 默认生成截图框宽度
        // autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [7, 5], // 截图框的宽高比例
        full: true, // 是否输出原图比例的截图
        canMoveBox: false, // 截图框能否拖动
        original: false, // 上传图片按照原始比例渲染
        centerBox: false, // 截图框是否被限制在图片里面
        infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
      },
      // 防止重复提交
      loading: false,
    };
  },
  computed:{
    // ...mapState("user",["pageNow"]),
    pageNow:{
      get(){
        return this.$store.state.user.pageNow
      },
      set(val){
          this.$store.state.user.pageNow = val
      }
    }
  },
  methods: {
    searchList(){
      
      this.$artcle.getaList({
        data:{
          [this.searchBy]:this.search
        }
      }).then(res =>{
        console.log(res);
        this.$emit("changeList",res.data)
      })
    },
    toCategory(){
      this.$router.push("/category")
    },
    changePasswords() {
      this.$userApi
        .changePassword({
          data: this.passwords,
        }).then(res=>{
          if(res.ret ===200){
            this.$message.success("密码修改成功")
          }else{
            this.$message.error("密码修改失败")
          }
        })
    },
    // 上传按钮   限制图片大小
    changeUpload() {
      // console.log(file);
      // this.fileinfo = file;
      // 上传成功后将图片地址赋值给裁剪框显示图片
      this.$nextTick(() => {
        console.log(this.imageUrl);
        this.option.img = this.imageUrl;
      });
    },
    // 点击裁剪，这一步是可以拿到处理后的地址
    finish() {
      this.$refs.cropper.getCropBlob((data) => {
        console.log(data);
        this.loading = true;
        let formData = new FormData();
        formData.append("file", data);
        this.$userApi
          .sendImg({
            data: formData,
          })
          .then((res) => {
            this.$userApi
              .changeUserImg({
                data: {
                  avatarUrl: res.data.url,
                },
              })
              .then((res) => {
                console.log(res);
                this.userInfo.avatar = res.data[0].avatar;
                this.loading = false;
                this.dialogVisible = false;
                this.imgView = false;
              });
          });
      });
    },

    exitLogin() {
      if (localStorage.getItem("userData")) {
        localStorage.removeItem("userData");
      }
      this.$userApi.exitLogin()
       this.$router.push("/login");

    },
    cImg(url) {
      console.log(url);
      let formData = new FormData();
      formData.append("file", url);
      this.$userApi
        .sendImg({
          data: formData,
        })
        .then((res) => {
          if (res.ret === 200) {
            this.$userApi
              .changeUserImg({
                data: {
                  avatarUrl: res.data.url,
                },
              })
              .then((res) => {
                this.userInfo.avatar = res.data[0].avatar;
                console.log(res);
                this.imgView = false;
              });
          }
        });
    },
    handleAvatarSuccess(res, file) {
      console.log(file);
      this.imgFile = file;
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type.includes("image");
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("请上传图片");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  beforeCreate() {
    // this.$store.dispatch("user/getUserInfo")
    this.$userApi.getUserInfo().then((res)=>{
      // console.log(res);
      this.$store.commit("user/setInfo",res.data)
      // console.log( this.$store.state.user.userInfo);
      this.userInfo = this.$store.state.user.userInfo
      
    })
    
  },
  mounted() {
    // console.log(this.$store.state.user);
    // console.log(this.userInfo)
    // let arr = mapState("user",["userInfo"])
    
    // console.log(mapState("user",["userInfo"]))
    // console.log(arr.userInfo);

  },

 
};
</script>

<style lang="scss" scoped>
// 截图
.cropper-content {
  .cropper {
    width: auto;
    height: 300px;
  }
}
.layout {
  border: 1px solid #d7dde4;
  background: #f5f7f9;
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  min-width: 802px;
  .ivu-menu {
    display: flex;
  }
  .ivu-icon-md-search {
    margin-left: 5px;
    font-size: 22px;
  }

  .ivu-radio-wrapper {
    background: #515a6e;
    color: white;
  }
  .ivu-radio-wrapper:hover {
    border-color: #2d8cf0;
  }
}
.link-to-per {
  color: #515a6e;
}
.layout-logo {
  width: 150px;
  height: 45px;
  background: #5b6270;
  border-radius: 3px;
  float: left;
  position: relative;
  top: 10px;
  left: -10px;

  font-size: 24px;
  line-height: 45px;
  white-space: nowrap;
  a {
    color: white;
  }
}
.layout-nav {
  margin: 0 auto;
  margin-right: -50px;
  white-space: nowrap;
  .ivu-menu-item {
    font-size: 16px;
  }
}
.userImg {
  width: 40px;
  border-radius: 5px;
  position: relative;
  top: 12px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.pwsWrap {
  .ivu-input-wrapper {
    margin-bottom: 15px;
  }
}
</style>